﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using MassIntellect;

using System.Xml.Linq;
using System.ComponentModel;
using MassIntellect.WorkIt;

namespace AIS2
{
    /// <summary>
    /// Служба доступа к данным
    /// </summary>
    public class DAService : WorkFrame, IDAService
    {
		[Serialize]
		[Description("Таймаут ожидания соединения с базой данных")]
		public int DatabaseTimeout { get; set; }

        private static DAService _Instance;
        public static DAService Instance
        {
            get
            {
                return _Instance ?? new DAService();
            }
            set
            {
                _Instance = value;
            }
        }

        protected override void protectedPulse(PulseArgs args)
        {
            TestConnection();
            base.protectedPulse(args);
        }

        public DAService()
            : base()
        {
            if (_Instance == null)
                _Instance = this;
        }

        [Serialize]
        public string ConnectionString { get; set; }

        public DataAccess.AIS2_DataDataContext GetContext()
        {
			var db = new DataAccess.AIS2_DataDataContext(ConnectionString);
			db.CommandTimeout = DatabaseTimeout;
			return db;
        }


        /// <summary>
        /// Тестировать соединение
        /// </summary>
        /// <returns></returns>
        public void TestConnection()
        {
            using (var db = GetContext())
            {
				db.CommandTimeout = DatabaseTimeout;
                try
                {
                    db.Connection.Open();
                }
                finally
                {
                    db.Connection.Close();
                }
            }
        }
    }
}
